package com.zx.framework.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.zx.framework.core.exception.ServiceException;

public class StreamUtil extends IOUtils {
	
	private static Logger LOG = Logger.getLogger(StreamUtil.class);
	/**
	 * 将对象写入文件
	 * @param o
	 * @param dataFile
	 */
	public static void writeObjectForFile(Object o,File dataFile){
		ObjectOutputStream oos =null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(dataFile));
			oos.writeObject(o);
		} catch (FileNotFoundException e) {
			LOG.error("", e);
			throw new ServiceException(e);
		} catch (IOException e) {
			LOG.error("", e);
			throw new ServiceException(e);
		}catch (Exception e) {
			LOG.error("", e);
			throw new ServiceException(e);
		}finally{
			if(ObjectUtils.isNotNull(oos)){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 将对象写入文件
	 * @param o
	 * @param dataFile
	 */
	public static void writeObjectForFile(Object o,String dataFile){
		File file = new File(dataFile);
		writeObjectForFile(o, file);
	}
	/**
	 * 读取文件中的对象
	 * @param dataFile
	 * @return
	 */
	public static <T extends Object> T readObjectForFile(File dataFile){
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(dataFile));
			return (T) ois.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new ServiceException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new ServiceException(e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}finally{
			if(ObjectUtils.isNotNull(ois)){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 读取文件中的对象
	 * @param dataFile
	 * @return
	 */
	public static <T extends Object> T readObjectForFile(String dataFile){
		return readObjectForFile(new File(dataFile));
	}
}
